#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests
import urllib3
import hashlib
from Crypto.Hash import SHA1
from binascii import hexlify   #返回的二进制数据的十六进制表示
import random
import time
urllib3.disable_warnings()
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(f'pj.log', encoding='utf-8')
file_handler.setLevel(logging.INFO) 
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)

class PJ():
    def __init__(self, token:str,userNo: str) -> None:
        self.logger = logger
        self.logger.info(f"{userNo}-开始执行")
        self.requests = requests.session()
        self.token = token
        self.userNo = userNo
        result = str(random.sample(range(1, 101), 10))
        steamid_sha1_hash = SHA1.new(result.encode('ascii')).digest()
        h = hexlify(steamid_sha1_hash).decode('ascii')      #码流转换
        deviceid = "%s-%s-%s" % (h[0:7], h[8:12], h[13:16]) 
        self.deviceid = deviceid
        self.headers = {
            "Host": "jxpc.cdut.edu.cn",
            "Connection": "close",
            "Accept": "application/json, text/plain, */*",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
            "Referer": "http://jxpc.cdut.edu.cn/static/vue/vue/index.html",
            "Accept-Language": "zh-CN,zh",
            "Cookie": "token="+token+"; userNo="+userNo
        }
        
    def md5(self,courseinfo):
        if(courseinfo['commentator']!=""): string = courseinfo['commentator']
        else: string = ""
        if(courseinfo['basicParams']!=""): string = string + courseinfo['basicParams']
        if(courseinfo['param1']!=""): string = string + courseinfo['param1']
        if(courseinfo['param2']!=""): string = string + courseinfo['param2']
        if(courseinfo['param3']!=""): string = string + courseinfo['param3']
        if(courseinfo['param4']!=""): string = string + courseinfo['param4']
        string = string + "murp2020"
        md5 = hashlib.md5()
        md5.update(string.encode('utf-8'))
        return md5.hexdigest()

    def getpjlist(self):
        url = "http://jxpc.cdut.edu.cn/api/v2/pj/all/list?token="+self.token
        res = self.requests.get(url=url,headers=self.headers,verify=False).json()
        if(res['state']==200):
            return res['data']
        else:
            self.logger.info("获取评教列表出错！返回信息："+res['msg'])
            exit()

    def enterpj(self,courseID:str,XSPJID:str):
        url = "http://jxpc.cdut.edu.cn/api/v2/pj/jumpToPaper?token="+self.token+"&id="+courseID
        res = self.requests.get(url=url,headers=self.headers,verify=False).json()
        if(res['state']==200): 
            url = "http://jxpc.cdut.edu.cn/api/v2/questionnaire/paper/"+XSPJID+"?token="+self.token
            self.requests.get(url=url,headers=self.headers,verify=False)
            self.logger.info("开始填写...",res['data'])
            return res['data']
        else:
            self.logger.info("获取课程信息出错！返回信息："+res['msg'])
            exit()

    def randomscore(self):
        t = random.uniform(0.85,1)
        result = "{:.2f}".format(t)
        return result+"0000"
    
    def formpj(self,courseinfo: dict,XSPJID: str):
        url = "http://jxpc.cdut.edu.cn/api/v2/questionnaire/paper/"+XSPJID+"?token="+self.token
        answers = {
                "s09568d26ad9944fdb5a15d867617f5f8": {
                    "result": self.randomscore()
                },
                "se83b0fef01234f0392941fc016010cc8": {
                    "result": self.randomscore()
                },
                "sdaeef8d64ab44e4bb1638b25a33a512f": {
                    "result": self.randomscore()
                },
                "sd25ed5ee95e24d13a2825a8fe8001d27": {
                    "result": self.randomscore()
                },
                "sc941b55fc4db49bc9cfc94a628bdf937": {
                    "result": self.randomscore()
                },
                "s6dfd3fd7d828450296886cdd7be5219f": {
                    "result": self.randomscore()
                },
                "s7fb097d482944294a39a447d59796794": {
                    "result": self.randomscore()
                },
                "s768b6c51da134fdca24d1176be5c062a": {
                    "result": self.randomscore()
                },
                "s0507efef58714dd4837088d04c71cea7": {
                    "result": self.randomscore()
                },
                "s550e0a12e5f34d26b5ca960c02396d2a": {
                    "result": self.randomscore()
                },
                "sddd59e64f066496f8ffa66353ce3316d": {
                    "result": "无"
                }
            }
        data = {
            "status": "0",
            "basicParams": courseinfo['basicParams'],
            "param1": courseinfo['param1'],
            "param2": courseinfo['param2'],
            "param3": courseinfo['param3'],
            "param4": courseinfo['param4'],
            "commentator": courseinfo['commentator'],
            "deviceId": self.deviceid,
            "signature": "",
            "answers": answers,
            "verification": self.md5(courseinfo)
        }

        
        headers = self.headers
        #headers.update({"Content-Type": "application/json;charset=UTF-8"})

        res = self.requests.post(url=url,headers=headers,json=data,verify=False).json()
        self.logger.info(res)
        data['status'] = "1"
        #data = data.replace("status\": \"0","status\": \"1")
        res = self.requests.post(url=url,headers=headers,json=data,verify=False).json()
        self.logger.info(res)

def getpjlist(token,userNo):
    pj = PJ(token,userNo)
    logger.info(f"获取评教列表:user:{userNo},token:{token}")
    return pj.getpjlist()
def log(text):
    logger.info(text)

def start(token,userNo,courseinfo):
    pj = PJ(token,userNo)
    logger.info("课程名称："+courseinfo['COURSENAME']+" | 老师："+courseinfo['TEACHERNAME'])
    courseID = courseinfo['ID']
    XSPJID = courseinfo['XSPJID']
    courseinfo = pj.enterpj(courseID,XSPJID)
    sleeptime = random.randint(10,30)
    logger.info("等待{}秒".format(sleeptime))
    time.sleep(sleeptime)
    pj.formpj(courseinfo,XSPJID)
    return None
     